package com.itheima.dao.impl;

import com.itheima.dao.AdminDao;
import com.itheima.domain.Admin;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;


@Repository(value = "adminDao")
public class AdminDaoImpl implements AdminDao {

    @Autowired
    @Qualifier(value = "queryRunner")
    private QueryRunner queryRunner;

    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    @Override
    public List<Admin> findAll() {
        try {
            List<Admin> list = queryRunner.query(
                    "select * from admin",
                    new BeanListHandler<Admin>(Admin.class)
            );
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Admin findOne(Integer id) {
        try {
            Admin one = queryRunner.query(
                    "select * from admin where id = ?",
                    new BeanHandler<Admin>(Admin.class),
                    id
            );
            return one;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Integer save(Admin admin) {
        try {
            int update = queryRunner.update(
                    "insert into admin (username, address) values(?, ?)",
                    admin.getUsername(), admin.getAddress()
            );
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer update(Admin admin) {
        try {
            int update = queryRunner.update(
                    "update admin set username = ?, address = ? where id = ?",
                    admin.getUsername(), admin.getAddress(), admin.getId()
            );
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer delete(Integer id) {
        try {
            int update = queryRunner.update(
                    "delete from admin where id = ?",
                    id
            );
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }
}
